package com.voice.server.observer.impl;

import com.voice.server.command.MessageCommand;
import com.voice.server.entity.AppToken;
import com.voice.server.enums.PushTypeEnum;
import com.voice.server.observer.Observable;
import com.voice.server.observer.Observer;
import com.voice.server.repository.AppTokenRepository;
import com.wangjiacai.utils.web.service.RedisService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class ApiObserver implements Observer, InitializingBean {

    public static String hashKey = "pushUrl";

    @Autowired
    private AppTokenRepository appTokenRepository;
    @Autowired
    private RedisService redisService;
    @Autowired
    private Map<String, MessageCommand> commandMap;

    @Override
    public void afterPropertiesSet() throws Exception {
        List<AppToken> list = appTokenRepository.findByPushUrlIsNotNull();
        list.stream().forEach(appToken -> redisService.hashSet(hashKey, appToken.getUserId(), appToken));
    }

    @Override
    public void update(Observable observable, String userId, String deviceKey, Object data, Object... param) {
        if (redisService.hashGet(hashKey, userId) == null) return;
        String pushType = (String) param[0];
        if (pushType == null) pushType = PushTypeEnum.Text.getKey();
        MessageCommand command = commandMap.get(pushType);
        command.executeApi(userId, deviceKey, data);
    }

}
